package bupt.xixi.learning.beans.factory.support;

import bupt.xixi.learning.beans.BeansException;
import bupt.xixi.learning.beans.factory.DisposableBean;
import bupt.xixi.learning.beans.factory.config.BeanDefinition;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;

import java.lang.reflect.Method;


public class DisposableBeanAdapter implements DisposableBean {

    private Object bean;
    private String beanName;
    private String destroyMethodName;

    public DisposableBeanAdapter(Object bean, String beanName, BeanDefinition beanDefinition) {
        this.bean = bean;
        this.beanName = beanName;
        this.destroyMethodName = beanDefinition.getDestroyMethodName();
    }

    @Override
    public void destroy() throws Exception {
        // 1. 实现接口DisposableBean
        if (this.bean instanceof DisposableBean) {
            ((DisposableBean) bean).destroy();
        }

        // 2. 配置destroy-method
        if (StrUtil.isNotEmpty(destroyMethodName) && !(bean instanceof DisposableBean && "destroy"
                .equals(this.destroyMethodName))) {
            Method destroyMethod = bean.getClass().getMethod(destroyMethodName);
            if (null == destroyMethod) {
                throw new BeansException(
                        String.format("Couldn't not find a destroy method named '%s' on bean with name '%s'",
                                      this.destroyMethodName,
                                      this.beanName));
            }

            destroyMethod.invoke(bean);
        }
    }
}
